﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Runtime.Remoting.Channels;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
using Communication.Channel;
using Communication.Message.Osc;
using Growatt.DuiHelpers;
using growatt.Message.Osc;
using Growatt.WaveData.DataSetResolve;
using LEDVANCE.Oscilloscope.VirtualOscilloscope.DataGridViewHelper;
using Oscilloscope.Util;
using Sunny.UI;
using Vosc;
using Vosc.VirtualOscilloscope;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace Growatt.WaveData.VirtualOscilloscope
{
    public partial class UC_ParameterWriting : UserControl
    {
        DatagirdViewHelper datagirdViewHelper = null;

        private UIComboDataGridView comboBox_Selecet = new UIComboDataGridView()
        {
            DropDownWidth = 500,
            ForeColor = Color.Blue,
            DropDownStyle = UIDropDownStyle.DropDown,
            Font = new System.Drawing.Font("宋体", 8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))),
        };
        ModelSaveString model = new ModelSaveString();
        private BindingSource bindingSource;

        public UC_ParameterWriting()
        {
            InitializeComponent();
            textBoxScale.SelectedIndex = 0;
            textBoxType.SelectedIndex = 0;
            MainForm.getChannelHelper += (s) =>
            {
                channel = s;
            };
            textBoxName.Text = OscilloscopeControl.ModelAppSettingsCustom.WriteValueName;
            textBox_WriteVal.Text = OscilloscopeControl.ModelAppSettingsCustom.WriteValue;
            model.Name = OscilloscopeControl.ModelAppSettingsCustom.WriteValueName;
            comboBox_Selecet.Text = OscilloscopeControl.ModelAppSettingsCustom.WriteValueName;
            // 创建 BindingSource
            bindingSource = new BindingSource();
            bindingSource.DataSource = model;

            // 绑定属性到 TextBox

            comboBox_Selecet.DataGridView.Init();
            comboBox_Selecet.DataGridView.MultiSelect = true; //设置可多选
            comboBox_Selecet.ItemSize = new System.Drawing.Size(500, 200);

            comboBox_Selecet.DataGridView.AddColumn("参数名称", "Name", fillWeight: 40);
            comboBox_Selecet.DataGridView.AddColumn("类型", "Type", fillWeight: 20);
            comboBox_Selecet.DataGridView.AddColumn("倍率", "Scale", fillWeight: 20);
            comboBox_Selecet.DataGridView.AddColumn("地址", "Address", fillWeight: 40);
            //comboBox_Selecet.DataGridView.AddColumn("偏移", "SignalOffset", fillWeight: 40);
            //comboBox_Selecet.DataGridView.AddCheckBoxColumn(
            //    "删除",
            //    "IsSelected",
            //    fillWeight: 30,
            //    readOnly: false
            //);
            comboBox_Selecet.DataGridView.ReadOnly = false;
            comboBox_Selecet.ShowFilter = false;

            comboBox_Selecet.Filter1by1 = false;
            datagirdViewHelper = new DatagirdViewHelper(comboBox_Selecet.DataGridView);
            HideControlsWithTextHelper.HideControlsWithText(comboBox_Selecet.item, "删除");
            HideControlsWithTextHelper.HideControlsWithText(comboBox_Selecet.item, "搜索");
            comboBox_Selecet.ShowText = true;
            comboBox_Selecet.BackColor = Color.Red;
            comboBox_Selecet.ForeColor = Color.Gray;
            // 绑定事件
            comboBox_Selecet.ValueChanged += new Sunny.UI.UIComboDataGridView.OnValueChanged(this.uiComboDataGridView2_ValueChanged);

            comboBox_Selecet.Dock = DockStyle.Top;
            comboBox_Selecet.ForeColor = Color.Black;
            comboBox_Selecet.Font = new System.Drawing.Font("微软雅黑", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            comboBox_Selecet.Filter1by1 = false;
            comboBox_Selecet.FilterChanged += UiComboDataGridView2_FilterChanged;
            comboBox_Selecet.Dock = DockStyle.Fill;
            panel1.Controls.Add(comboBox_Selecet);
        }

        // Token: 0x040000AC RID: 172
        public Channel channel;

        public enum ScaleDataType
        {
            x1 = 1,
            x10 = 10,
            x100 = 100,
            x1k = 1000,
            x10k = 10000,
            x100k = 100000,
        }

        ModelSaveString selectParaInfo = null;

        private void uiComboDataGridView2_ValueChanged(object sender, object value)
        {
            if (value != null && value is DataGridViewSelectedRowCollection)
            {
                DataGridViewSelectedRowCollection collection = (DataGridViewSelectedRowCollection)value;
                foreach (var item in collection)
                {
                    DataGridViewRow row = (DataGridViewRow)item;
                    selectParaInfo = row.DataBoundItem as ModelSaveString;
                    textBoxAddress.Text = selectParaInfo.Address;
                    textBoxType.Text = selectParaInfo.Type;
                    textBoxScale.Text = selectParaInfo.Scale;
                    itemConfigCurrent = selectParaInfo;
                    textBoxName.Text = selectParaInfo.Name;
                    comboBox_Selecet.Text = selectParaInfo.Name;
                }
            }
        }

        ModelSaveString itemConfigCurrent = null;
        public Action<string> ActionShow { get; set; }

        private void UiComboDataGridView2_FilterChanged(object sender, UIComboDataGridViewArgs e)
        {
            datagirdViewHelper.SearchModels(e.FilterText);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                ActionShow?.Invoke($"");
                if (!string.IsNullOrEmpty(textBoxName.Text) && !string.IsNullOrEmpty(textBox_WriteVal.Text) && textBoxScale.SelectedIndex != -1 && textBoxType.SelectedIndex != -1)
                {
                    List<string> strings = new List<string>() { textBoxName.Text };
                    ENUM_001 ty_ENUM_001 = ENUM_001.I16;

                    VariableInfo variableInfo = new VariableInfo(textBoxName.Text, string.Empty);
                    DwarfHelper.DwarfHelperInstance.GetAddress(new List<VariableInfo>() { variableInfo });
                    if (string.IsNullOrEmpty(variableInfo.Address))
                    {
                        MessageBox.Show("查询失败");
                        return;
                    }
                    var typeString = string.Empty;

                    if (!string.IsNullOrEmpty(variableInfo.SzieVar))
                    {
                        // 使用MessageBox询问是否继续
                        //DialogResult result = MessageBox.Show($"当前变量的类型:{variableInfo.SzieVar},是否继续设置?", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        //if (result != DialogResult.Yes)
                        //{
                        //    return;
                        //}
                        typeString = variableInfo.SzieVar;
                        if (typeString.Contains("unsigned"))
                        {
                            ty_ENUM_001 = ENUM_001.U16;
                        }
                        else if (typeString.Contains("float"))
                        {
                            ty_ENUM_001 = ENUM_001.F32;
                        }
                        else
                        {
                            ty_ENUM_001 = ENUM_001.I16;
                        }
                        textBoxType.Text = Enum.GetName(typeof(ENUM_001), ty_ENUM_001);
                    }
                    if (!string.IsNullOrEmpty(variableInfo.Address))
                    {
                        double dataf = 1;
                        if (Enum.TryParse(textBoxScale.Text, out ScaleDataType type) && double.TryParse(textBox_WriteVal.Text, out double valToSet))
                        {
                            dataf = (double)type * dataf * valToSet;
                        }
                        if (dataf.ToString().Contains("-"))
                        {
                            if (!(dataf >= 32767 && dataf <= -32768))
                            {
                                MessageBox.Show($"当前设置数据为:{dataf.ToString()},超出数据范围(-32768~32767),请重新输入!");
                                return;
                            }
                        }
                        else
                        {
                            if (ty_ENUM_001 == (ENUM_001.U16) || ty_ENUM_001 == (ENUM_001.F32))
                            {
                                if (!(dataf >= 0 && dataf <= 65535))
                                {
                                    MessageBox.Show($"当前设置数据为:{dataf.ToString()},超出数据范围(0~65535),请重新输入!");
                                    return;
                                }
                            }
                            if (ty_ENUM_001 == (ENUM_001.I16))
                            {
                                if (!(dataf >= 32767 && dataf <= -32768))
                                {
                                    MessageBox.Show($"当前设置数据为:{dataf.ToString()},超出数据范围(-32768~32767),请重新输入!");
                                    return;
                                }
                            }
                        }

                        var f = variableInfo.Address;
                        Console.WriteLine($"地址:{f} 设置的数据:{dataf}");
                        var ad = Convert.ToInt32(f, 16);
                        var SignalRatio = (byte)(ENUM_Ratio)Enum.Parse(typeof(ENUM_Ratio), (string)textBoxScale.SelectedItem); //数据倍率
                        var SignalType = (byte)(ENUM_001)Enum.Parse(typeof(ENUM_001), (string)textBoxType.SelectedItem); //数据类型
                        var ty = (ENUM_001)Enum.Parse(typeof(ENUM_001), (string)textBoxType.SelectedItem);
                        byte reType = 0;
                        if (typeString.Contains("unsigned"))
                        {
                            ty = ENUM_001.U16;
                        }
                        else if (typeString.Contains("float"))
                        {
                            ty = ENUM_001.F32;
                        }
                        else
                        {
                            ty = ENUM_001.I16;
                        }
                        switch (ty)
                        {
                            case ENUM_001.U16:
                                reType = 0;
                                break;

                            case ENUM_001.I16:
                                reType = 1;
                                break;
                            case ENUM_001.F32:
                                reType = 2;
                                break;
                            default:
                                break;
                        }
                        ConfigDataChanelMessage addrSetChannelMessage = new ConfigDataChanelMessage(new int[] { ad }, reType, SignalRatio, (int)dataf); //发送所有地址信息(地址设置)
                        addrSetChannelMessage.SetSendTimeoutMillis(1000);
                        addrSetChannelMessage.SetSpaceReceiveTimeoutMillis(1000);
                        addrSetChannelMessage.SetTotalReceiveTimeoutMillis(1000);

                        try
                        {
                            var val = MainForm.ChannelWriters?.Invoke(addrSetChannelMessage);
                            if (!val.Value)
                            {
                                channel?.Close();
                                return;
                            }
                            Thread.Sleep(300);
                            MessageBox.Show($"下发设置参数成功,地址:{f}");
                            channel?.Close();
                        }
                        catch (Exception ex)
                        {
                            DuiHelperLog.WriteErrorLog(ex);
                        }
                    }
                    else
                    {
                        ActionShow?.Invoke($"请检查是否存在当前变量");
                        Console.WriteLine("请检查是否存在当前变量!");
                    }
                }
                else
                {
                    ActionShow?.Invoke($"请检查输入值!");
                    Console.WriteLine("请检查输入值");
                }
            }
            catch (Exception ex)
            {
                DuiHelperLog.WriteErrorLog(ex);
            }
            finally
            {
                channel?.Close();
            }
        }

        private void textBox_ParaName_TextChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(textBoxName.Text))
                OscilloscopeControl.ModelAppSettingsCustom.WriteValueName = textBoxName.Text;
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(textBox_WriteVal.Text))
                OscilloscopeControl.ModelAppSettingsCustom.WriteValue = textBox_WriteVal.Text;
        }
    }
}
